package com.qzuser.sendmessagebasic.server.dao;

import com.qzuser.sendmessagebasic.SendMessageBasicApplication;
import com.qzuser.sendmessagebasic.common.exception.DataBaseException;
import com.qzuser.sendmessagebasic.server.binding.Binding;
import com.qzuser.sendmessagebasic.server.exchange.Exchange;
import com.qzuser.sendmessagebasic.server.exchange.ExchangeType;
import com.qzuser.sendmessagebasic.server.mapper.MetaMapper;
import com.qzuser.sendmessagebasic.server.queue.Queue;

import java.io.File;
import java.io.IOException;
import java.util.List;

public class DataBase {
    private MetaMapper metaMapper;
    public void init() throws DataBaseException {
        metaMapper = SendMessageBasicApplication.context.getBean(MetaMapper.class);
        File dir = new File("./data");
        if (!dir.exists()) {
            if (!dir.mkdir()) {
                throw new DataBaseException("[DataBase] 数据目录创建失败：" + dir.getAbsolutePath());
            }
        }
        File db = new File("./data/meta.db");
        if (!db.exists()) {
            try {
                boolean ok = db.createNewFile();
            } catch (IOException e) {
                throw new DataBaseException("[DataBase] 数据库文件创建失败：" + db.getAbsolutePath());
            }
        }
        metaMapper.createExchangeTable();
        metaMapper.createQueueTable();
        metaMapper.createBindingTable();
        initData();
    }

    private void initData() {
        if (getExchange() != null) {
            return;
        }
        Exchange exchange = new Exchange();
        exchange.setName("");
        exchange.setType(ExchangeType.DIRECT);
        exchange.setDurable(true);
        exchange.setAutoDelete(false);
        metaMapper.insertExchange(exchange);
    }

    public void deleteDB() throws DataBaseException {
        boolean ok = new File("./data/meta.db").delete();
        boolean ok2 = new File("./data").delete();
        if (!ok || !ok2) {
            throw new DataBaseException("[DataBase] 数据库文件删除失败");
        }
    }

    private Exchange getExchange() {
        return metaMapper.getExchange();
    }

    public void insertExchange(Exchange exchange) {
        metaMapper.insertExchange(exchange);
    }

    public void deleteExchange(String exchangeName) {
        metaMapper.deleteExchange(exchangeName);
    }

    public List<Exchange> getExchanges() {
        return metaMapper.getExchanges();
    }

    public void insertQueue(Queue queue) {
        metaMapper.insertQueue(queue);
    }

    public void deleteQueue(String queueName) {
        metaMapper.deleteQueue(queueName);
    }

    public List<Queue> getQueues() {
        return metaMapper.getQueues();
    }

    public void insertBinding(Binding binding) {
        metaMapper.insertBinding(binding);
    }

    public void deleteBinding(Binding binding) {
        metaMapper.deleteBinding(binding);
    }

    public List<Binding> getBindings() {
        return metaMapper.getBindings();
    }
}
